<?php
namespace app\admin\model;
use think\Config;
use think\Db;
class ToolModel extends \app\common\model\CommonModel
{
    /**
     * @param int       $catid
     * @param string    $name
     * @param int       $pagesize
     * @param int       $page
     */
    public function list($params)
    {
        try {
            $page     = isset($params['page']) && is_numeric($params['page']) ? (int)$params['page'] : 1;
            $pagesize = isset($params['pagesize']) && is_numeric($params['pagesize']) ? (int)$params['pagesize'] : 10;
            $start = ($page-1) * $pagesize;
            $field = "a.id,a.catid,b.cat,a.icon,a.name,a.path,a.status,a.visible,a.`desc`,a.tags,a.sort";
            $sql = "SELECT {$field} FROM tool a LEFT JOIN cat b ON a.catid = b.id WHERE 1 = 1 ";
            if(!empty($params['catid'])){
                $sql .= "AND `catid` = {$params['catid']} ";
            }
            if(!empty($params['name'])){
                $sql .= "AND `name` LIKE '%{$params['name']}%' ";
            }
            $order = "ORDER BY sort DESC LIMIT {$start},{$pagesize}";
            $csql = str_replace($field,'count(*)',$sql);
            $sql .= $order;
            $res = $this->getRes($sql);
            $count = $this->getCount($csql);
            return $this->pageData($res,$pagesize,$page,$count);   
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }    
    }

    /**
     * @param string    $icon
     * @param int       $catid
     * @param string    $name
     * @param string    $path
     * @param string    $desc
     * @param string    $tags
     */
    public function addTool($params)
    {
        try {
            if(!Db::table('cat')->where(['id' => $params['catid']])->find()){
                throw new \Exception("此分类不存在!");    
            }
            if(Db::table('tool')->where(['name' => trim($params['name'])])->find()){
                throw new \Exception("工具名称已存在!");    
            }
            if(Db::table('tool')->where(['path' => trim($params['path'])])->find()){
                throw new \Exception("工具路径已存在!");
            }
            //获取排序值
            $sortinfo = Db::table('tool')->order('sort desc')->limit(1)->find();
            $sort = empty($sortinfo['sort']) ? 1 : $sortinfo['sort'] + 1;
            if(Db::table('tool')->insert([
                'icon' => trim($params['icon']),
                'catid' => (int)$params['catid'],
                'name' => trim($params['name']),
                'path' => trim($params['path']),
                'desc' => trim($params['desc']),
                'status' => 1,
                'visible' => 1,
                'sort' => $sort,
                'tags' => $params['tags']])){
                return true;
            }
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除工具
     * @param int $toolid
     */
    public function deleteTool($toolid)
    {
        try {
            if(Db::table('tool')->where(['id' => $toolid])->delete() !== false){
                return true;
            }
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 状态开关
     * @param int $toolid
     * @param int $status
     */
    public function editToolStatus($data)
    {
        try {
            if(Db::table('tool')->where(['id' => (int)$data['toolid']])->update(['status' => (int)$data['status']]) !== false){
                return true;
            }    
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }    
    }

    /**
     * 可见开关
     * @param int $toolid
     * @param int $visible
     */
    public function editToolVisible($data)
    {
        try {
            if(Db::table('tool')->where(['id' => (int)$data['toolid']])->update(['visible' => (int)$data['visible']]) !== false){
                return true;
            }    
            return false;    
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }    
    }

    /**
     * 编辑工具信息
     * @param int       $toolid
     * @param string    $icon
     * @param int       $catid
     * @param string    $name
     * @param string    $path
     * @param string    $desc   
     */
    public function editToolInfo($data)
    {
        try {
            if(!Db::table('cat')->where(['id' => $data['catid']])->find()){
                throw new \Exception("此分类不存在!");    
            }
            if(Db::table('tool')->where("`id` != {$data['toolid']}")->where(['name' => trim($data['name'])])->find()){
                throw new \Exception("工具名称已存在!");    
            }
            if(Db::table('tool')->where("`id` != {$data['toolid']}")->where(['path' => trim($data['path'])])->find()){
                throw new \Exception("工具路径已存在!");
            }
            if(Db::table('tool')->where(['id' => $data['toolid']])->update([
                'icon'  => trim($data['icon']),
                'catid' => (int)$data['catid'],
                'name'  => trim($data['name']),
                'path'  => trim($data['path']),
                'desc'  => trim($data['desc']),
                'tags' => $data['tags']]) !== false){
                return true;
            }
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 工具排序
     * @param int old
     * @param int new 
     */
    public function sortTool($old,$new)
    {
        try {
            //数据库原始排序数据
            $list = Db::table('tool')->field('id,sort')->order('sort desc')->select();
            $idArr = [];
            $sortArr = [];
            foreach ($list as $item) {
                $idArr[] = $item['id'];
                $sortArr[] = $item['sort'];
            }
            //记录要拖动的id
            $oldValue = $idArr[$old];
            //删除这个要拖动的id
            unset($idArr[$old]);
            //插入新的位置，并自动移位
            array_splice($idArr, $new, 0, $oldValue);
            //重新设置排序
            $set = [];
            for ($i = 0; $i < count($idArr); $i++) {
                $set[$i]['id'] = $idArr[$i];
                $set[$i]['sort'] = $sortArr[$i];
            }
            $ids = array_column($set,'id');
            $ids = implode(',', array_column($set,'id'));
            $sql = "UPDATE `tool` SET `sort` = CASE id ";
            foreach ( $set as $key => $value) {
                $sql .= sprintf("WHEN %d THEN %d ", $value['id'], $value['sort']);
            }
            $sql .= "END WHERE `id` IN ($ids)";
            $res = Db::query($sql);
            return true;   
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());    
        }
    }

}